package db

import (
	"encoding/json"
	"errors"
	"sort"
	"strconv"
	"strings"
	"ulcdkey/tool"
)

/*

	角色管理

*/

//更新用户权限缓存
func (this *Role) CacheRoles() (err error) {

	rows, err := db.Query("SELECT  id,`name` , menuAuth ,gameAuth, platformAuth, `time` FROM `role` ;")

	if err != nil {
		return
	}

	defer rows.Close()
	temp := make(map[int]*Role)
	for rows.Next() {

		r := new(Role)
		err = rows.Scan(&r.Id, &r.Name, &r.MenuAuth, &r.GameAuth, &r.PlatformAuth, &r.Time)
		if err != nil {
			return
		}

		temp[r.Id] = r
	}

	RolesList = temp
	return
}

// 获取角色列表
func (this *Role) GetRoles() (rs []*Role, err error) {

	rs = []*Role{}

	keys := []int{}
	for id, _ := range RolesList {
		keys = append(keys, id)
	}

	sort.Ints(keys)

	for _, r := range keys {

		rs = append(rs, RolesList[r])
	}
	return
}

// 获取角色列表
func (this *Role) GetRoleById(id int) (r *Role, err error) {

	r = RolesList[id]
	if r == nil {

		err = errors.New("非法角色Id")
		return
	}

	return
}

// 获取角色列表
func (this *Role) GetRoleByUserId(uid int) (r *Role, err error) {

	user := UserList[uid]
	if user == nil {

		err = errors.New("非法用户id")
		return
	}

	//	log.Println("GetRoleByUserId user:", user)
	r = RolesList[user.RoleId]
	if r == nil {

		err = errors.New("非法角色Id")
		return
	}

	//	log.Println("GetRoleByUserId r:", r)

	return
}

// 添加角色
func (this *Role) AddRole(info *tool.VisitUserInfo) (err error) {

	_, err = db.Exec("insert into role(name) values(?)", this.Name)
	if err != nil {
		return
	}

	err = this.CacheRoles()
	if err != nil {
		return
	}

	// 记录日志
	b, _ := json.Marshal(this)
	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, ActionType: LogActionType.Add, Module: "角色管理", OldContent: "", NewContent: string(b)}
	serverLog.RecordLog()

	return
}

// 更新角色的菜单权限
func (this *Role) UpdateRole(info *tool.VisitUserInfo) (err error) {

	old, err := this.GetRoleById(this.Id)
	if err != nil {
		return
	}
	_, err = db.Exec("update role set menuAuth = ?,gameAuth = ?,platformAuth = ?,name = ?  where id = ?",
		this.MenuAuth,
		this.GameAuth,
		this.PlatformAuth,
		this.Name,
		this.Id)

	if err != nil {
		return
	}

	err = this.CacheRoles() //更新用户权限map
	if err != nil {
		return
	}

	// 记录日志
	nb, _ := json.Marshal(this)
	ob, _ := json.Marshal(old)

	serverLog := &ServerLog{UserId: info.Uid, UserName: info.UserName, ActionType: LogActionType.Update, Module: "角色管理", OldContent: string(ob), NewContent: string(nb)}
	serverLog.RecordLog()

	return
}

/*



 */

// 获取角色的菜单权限展示
func (this *Role) GetMenuAuthTree(roleId int) (as []*AuthTree, err error) {

	r := RolesList[roleId]
	if r == nil {

		err = errors.New("角色不存在")
		return
	}

	arr := strings.Split(r.MenuAuth, ",")

	rows, err := db.Query("select id, name, pid from menu order by menuOrder")
	if err != nil {
		return
	}

	defer rows.Close()
	for rows.Next() {

		a := new(AuthTree)
		err = rows.Scan(&a.Id, &a.Name, &a.Pid)
		if err != nil {
			return
		}

		if tool.IsExist(arr, strconv.Itoa(a.Id)) {
			a.Checked = true
			a.Open = true
		}

		as = append(as, a)
	}
	return
}
